var net = require('net');
var dns = require('dns');

var servers = [
	['bj.ltc1btc.com', 2600],
	['gz.ltc1btc.com', 2600],
	['vip3129933.ltc1btc.com', 2700],
	['stratum.f2pool.com', 3333],
];

function run_one(host, port, cb)
{
	var now = new Date();
	dns.lookup(host, {
		'all': true
	}, function(err, addresses) {
//		console.log(addresses);
		if(err) {
			console.error('resolve %s failed: %s', host, err.message);
			cb(err);
			return;
		}

		console.log('resolve %s result:', host);
		for(var i = 0;i < addresses.length;i++) {
			var ip = addresses[i].address;
			console.log('\t%s: %s', i, ip);
		}
		var then = new Date();
		console.log('dns cost %s seconds', ((then-now)/1000).toFixed(4));
		now = then;

		var s = net.connect(port, host);
		s.on('error', function(err) {
			console.error('socket error: %s', err.message);
			//cb(err);
		});
		s.on('close', function() {
			console.log('socket closed');
			then = new Date();
			console.log('end cost %s seconds', ((then-now)/1000).toFixed(4));
			cb();
		});
		s.on('connect', function() {
			console.log('socket connected');
			then = new Date();
			console.log('connect cost %s seconds', ((then-now)/1000).toFixed(4));
			s.end();
			now = then;
		});
	})
}

function run_all(idx, cb)
{
	if(idx == servers.length) {
		cb();
		return;
	}

	var server = servers[idx];
	run_one(server[0], server[1], function() {
		run_all(idx + 1, cb);
	})
}

function main()
{
	run_all(0, function() {
		console.log('===========\n\n\n');
		setTimeout(main, 5000);
	})
}

main();
